<?php

namespace App\Kuafu\Pay\Jobs;

use App\Kuafu\Pay\BasePay;
use App\Kuafu\Pay\Enum\BasePayEnum;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Service\PayService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class PayPolling implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public  $tries = 51; //尝试 51 次
    private $payNo;

    const QUEUE_NAME = '{RMS-API-PAY}';

    /**
     * Create a new job instance.
     * @param string $payNo
     * @return void
     */
    public function __construct(string $payNo)
    {
        $this->payNo = $payNo;
    }

    /**
     * @throws \App\Kuafu\Pay\Exceptions\PayException
     * @throws \App\Kuafu\CustomerCoupon\Exceptions\CustomerCouponException
     * @throws \App\Kuafu\Order\Exceptions\OrderException
     */
    public function handle()
    {
        Log::info('PayPolling........' . $this->payNo);

        if (!$this->payNo) {
            Log::info("PayPolling payNo null");
            return;
        }

        // 查DB支付信息
        $payStream = PayStreamModel::getDataByPayNo($this->payNo);
        if (!$payStream) {
            return;
        }

        // 已经成功了 - 结束
        if ($payStream->payStatus == PayStreamModel::PAY_STATUS_1) {
            return;
        }

        // 每次间隔5s，最大延迟≈5分钟
        if ($this->attempts() >= $this->tries) {
            Log::info("payNo:{$this->payNo}未支付，自动关闭 start");

            // 关闭接口
            BasePay::instance($payStream->payChannel, $payStream->shopId, $payStream->sysType, $payStream->company)->closePay($this->payNo);
            Log::info("payNo:{$this->payNo}未支付，自动关闭 end");

            return;
        }

        list($result, $_) = PayService::sPayPolling($payStream);
        if ($result == 'release') {
            $this->release(6);
        }

        if ($result == 'delete') {
            $this->delete();
        }
    }
}
